package com.example.gameforum.controller;


import com.example.gameforum.entity.Post;
import com.example.gameforum.entity.User;
import com.example.gameforum.service.PostService;
import com.example.gameforum.utils.CommunityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class PostController {

    @Autowired
    private PostService postService;

    @RequestMapping("/fatie")
    public String faTie(HttpServletRequest request, String title, String content) {
        HttpSession session = request.getSession();
        User user= (User) session.getAttribute("user");
        Post post=new Post();
        post.setContext(content);
        post.setId(CommunityUtils.getRandomThreeNum());
        post.setPuser(user);
        post.setLikenum(0);
        post.setTime(new Date());
        post.setTitle(title);
        String url="images/"+CommunityUtils.getRandomOneNum()+".gif";
        post.setPictrue(url);
        postService.insertPost(post);
        List<Post> posts= (List<Post>) session.getAttribute("posts");
        posts.add(post);
        session.setAttribute("posts",posts);
        return "home";
    }

   @RequestMapping("/postpage/{id}")
    public String getPostPage(Model model, @PathVariable("id")int id){
        Post post=postService.getById(id);
        model.addAttribute("post",post);
        return "post";
   }
}
